package com.xunshangwang.pinhaohuo.ui.fragments;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.decorations.DividerItemDecoration;
import com.xunshangwang.pinhaohuo.entity.Shop;
import com.xunshangwang.pinhaohuo.entity.ShopDetail;
import com.xunshangwang.pinhaohuo.http.HttpTool;
import com.xunshangwang.pinhaohuo.http.JsonHttpHandler;
import com.xunshangwang.pinhaohuo.transformation.RoundedTransformation;
import com.xunshangwang.pinhaohuo.ui.activities.ShopDetailActivity;
import com.xunshangwang.pinhaohuo.widgets.LMSizeRecyclerView;
import com.xunshangwang.pinhaohuo.widgets.RefreshLayout;

import org.json.JSONObject;

import java.util.BitSet;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import tool.library.adapter.BaseRecyclerAdapter;
import tool.library.widget.LoadRecyclerView;

/**
 * Created by xzp on 16/1/25.
 */
public class MyShopFragment extends BaseFragment implements LoadRecyclerView.OnLoadListener,
        SwipeRefreshLayout.OnRefreshListener,BaseRecyclerAdapter.OnItemClickListener{
    private LMSizeRecyclerView mRecycler;
    private RefreshLayout mRefresh;
    private ShopAdapter mAdapter;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_my_collection,container,false);
        mRecycler= (LMSizeRecyclerView) view.findViewById(R.id.my_collection_list);
        mRecycler.setLayoutManager(new LinearLayoutManager(inflater.getContext()));
        mRecycler.setOnLoadListener(this);
        mRecycler.addItemDecoration(new DividerItemDecoration(inflater.getContext()){
            @Override
            protected boolean canDraw(int position) {
                if(position<mAdapter.getItemCount()-1)
                    return true;
                return false;
            }
        });
        mRefresh= (RefreshLayout) view.findViewById(R.id.refresh_layout);
        mRefresh.setOnRefreshListener(this);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mAdapter=new ShopAdapter(getContext());
        mAdapter.setOnItemClickListener(this);
        mRecycler.setAdapter(mAdapter);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefresh.setRefreshing(true);
                onRefresh();
            }
        }, 150);

    }

    @Override
    public void onItemClick(BaseRecyclerAdapter adapter, View item, int position) {
        Intent intent=new Intent(getContext(), ShopDetailActivity.class);
        intent.putExtra("id", mAdapter.getList().get(position).getShop_id());
        startActivity(intent);
    }

    @Override
    public void onLoad(LoadRecyclerView recyclerView) {
        StringBuilder builder=new StringBuilder("?g=Api&m=Favorites&a=lists");
        builder.append("&fav_type=0");
        builder.append("&offset="+mAdapter.getListSize());
        builder.append("&size="+LMSizeRecyclerView.SIZE);
        builder.append("&token=" + getMainApplication().getToken());
        JsonHttpHandler<List<Shop>> handler=new JsonHttpHandler<List<Shop>>() {
            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, List<Shop> errorResponse) {
                super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
                mRecycler.loadFinish();
            }

            @Override
            public List<Shop> parseData(JSONObject object) throws Throwable {
                return JSON.parseArray(object.getString("favoritesLists"),Shop.class);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Shop> response) {
                mAdapter.addAll(response);
                mRecycler.loadFinish(response);
            }
        };
        handler.setTag(getView());
        HttpTool.get(getContext(),builder.toString(),handler);
    }

    @Override
    public void onRefresh() {
        refreshCollections();
    }
    private void refreshCollections(){
        StringBuilder builder=new StringBuilder("?g=Api&m=Favorites&a=lists");
        builder.append("&fav_type=0");
        builder.append("&offset=0");
        builder.append("&size="+LMSizeRecyclerView.SIZE);
        builder.append("&token=" + getMainApplication().getToken());
        JsonHttpHandler<List<Shop>> handler=new JsonHttpHandler<List<Shop>>() {
            @Override
            public void onFinish() {
                super.onFinish();
                mRefresh.setRefreshing(false);
            }

            @Override
            public List<Shop> parseData(JSONObject object) throws Throwable {
                return JSON.parseArray(object.getString("favoritesLists"),Shop.class);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Shop> response) {
                mAdapter.setList(response);
                mRecycler.loadFinish(response);
            }
        };
        handler.setTag(getView());
        HttpTool.get(getContext(),builder.toString(),handler);

    }
    private void requestCollect(final int position){
        StringBuilder builder=new StringBuilder("?g=Api&m=Favorites&a=toggleFavorites");
        builder.append("&fav_type=0");
        builder.append("&fav_id="+mAdapter.getList().get(position).getShop_id());
        builder.append("&token=" + getMainApplication().getToken());
        JsonHttpHandler<String> handler=new JsonHttpHandler<String>() {
            @Override
            public void onStart() {
                super.onStart();
                mAdapter.getRequestState().set(position);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mAdapter.getRequestState().clear(position);
            }

            @Override
            public String parseData(JSONObject object) throws Throwable {
                return object.getString("is_favorites");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, String response) {
                if(TextUtils.equals(response,"0")){
                    mAdapter.getList().remove(position);
                    mAdapter.notifyItemRemoved(position);
                }
            }
        };
        handler.setTag(getView());
        HttpTool.get(getContext(), builder.toString(), handler);

    }
    private class ShopAdapter extends BaseRecyclerAdapter<Shop>{
        private BitSet mRequestState;
        public ShopAdapter(Context context) {
            super(context);
            mRequestState=new BitSet();
        }

        public BitSet getRequestState() {
            return mRequestState;
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            View view=LayoutInflater.from(getContext()).inflate(R.layout.shop_item, parent, false);
            return new ShopHolder(view);
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, int position) {
            ShopHolder shopHolder= (ShopHolder) holder;
            Shop shop=getList().get(position);
            Glide.with(MyShopFragment.this).load(shop.getShop_face())
                    .centerCrop()
                    .transform(new RoundedTransformation(getContext(),R.dimen.shop_face_rounded_size))
                    .into(shopHolder.shopImage);
            shopHolder.nameText.setText(shop.getShop_name());
            shopHolder.sellCountText.setText("销量:  "+shop.getSell_count());
        }
        private class ShopHolder extends ClickableViewHolder{
            ImageView shopImage;
            TextView nameText,sellCountText;
            Button collectBtn;
            public ShopHolder(View itemView) {
                super(itemView);
                shopImage= (ImageView) itemView.findViewById(R.id.shop_image);
                nameText= (TextView) itemView.findViewById(R.id.shop_name_text);
                sellCountText= (TextView) itemView.findViewById(R.id.shop_sell_count_text);
                collectBtn= (Button) itemView.findViewById(R.id.shop_collect_btn);
                collectBtn.setText("取消收藏");
                collectBtn.setBackgroundResource(R.drawable.shop_collect_bg);
                collectBtn.setTextColor(ContextCompat.getColor(getContext(), R.color.gray));
                collectBtn.setOnClickListener(this);
            }

            @Override
            public void onClick(View v) {
                if(v.getId()==R.id.shop_collect_btn){
                    int position=getAdapterPosition();
                    if(position!=RecyclerView.NO_POSITION)
                    {
                        if(mRequestState.get(position))
                            return;
                        requestCollect(position);
                    }
                }
                else
                    super.onClick(v);
            }
        }
    }
}
